package fr.gdi.android.news.api.oauth;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import fr.gdi.android.news.api.R;

public final class GetOAuthCredentialsTask extends AsyncTask<Void, Void, JSONObject> 
{
    ProgressDialog authDialog;

    private AbstractOAuthShareActivity parent;
    
    private IOAuthVerifyCallback callback;
    
    private HttpClient httpClient;
    
    public GetOAuthCredentialsTask(AbstractOAuthShareActivity parent, IOAuthVerifyCallback callback)
    {
        this.parent = parent;
        this.callback = callback;
        
        HttpParams parameters = new BasicHttpParams();
        HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(parameters, false);
        HttpConnectionParams.setTcpNoDelay(parameters, true);
        HttpConnectionParams.setSocketBufferSize(parameters, 8192);
        
        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);
        httpClient = new DefaultHttpClient(tsccm, parameters);
        
    }
    
    @Override
    protected void onPreExecute() 
    {
        authDialog = ProgressDialog.show(parent, 
            parent.getText(R.string.auth_progress_title), 
            parent.getText(R.string.auth_progress_text), 
            true, false);
    }

    @Override
    protected JSONObject doInBackground(Void... arg0) 
    {
        JSONObject json = null;
        HttpGet get = new HttpGet(parent.getVerifyUrl());
        try 
        {
            parent.getConsumer().sign(get);
            String response = httpClient.execute(get, new BasicResponseHandler());
            json = new JSONObject(response);
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    protected void onPostExecute(JSONObject json) 
    {
        authDialog.dismiss();
        if ( callback != null )
        {
            callback.execute();
        }
        
    }
}
